package org.pp.core;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.pp.util.JwtUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

public class AdminSessionUtil {

    public static  String getLoginUserNameKey(Long userId) {
        return AdminConstants.loginUserName + ":" + userId;
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static Long getUserId(){
        HttpServletRequest request = getRequest();
        String token= request.getHeader(AdminConstants.tokenHeader);
        if(StrUtil.isBlank(token)){
            throw BizErro.TOKEN_EXPIRE.erro();
        }
        //jwt去获的用户id
        Map<String, Object> payload = JwtUtil.getPayload(token);
        Object value = payload.get(AdminConstants.jwtLoginKey);
        //id没有超过long的话，value就是int,超过了Integer.MAX_VALUE,value就是long
        if(value instanceof Integer){
            return (long) (Integer)value;
        }else{
            return (Long)value;
        }
    }


    /**
     * 加密
     * @param password
     * @return
     */
    public static String encrypt(String password){
        return SecureUtil.md5(password);
    }

    /**
     *
     * @param password
     * @param encryption
     * @return
     */
    public static boolean checkPassword(String password,String encryption){
        return StrUtil.isNotBlank(password) &&  encrypt(password).equals(encryption);
    }

   /* public static void main(String[] args) {
        System.out.println(encrypt("aaabbb"));
    }*/
}
